import 'dart:convert';

import 'package:dali_ng_pera/manager/dnp_plugin_manager.dart';
import 'package:dali_ng_pera/net/dnp_net_manager.dart';
import 'package:dali_ng_pera/page/certification/model/dnp_from_common_model.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart' as dio;

class DnpFromCommonController extends GetxController {
  // 存储表单数据
  final Rx<DnpFromCommonModel?> formModel = Rx<DnpFromCommonModel?>(null);

  // 动态创建的控制器映射，key 是 iesous（字段标识）
  final Map<String, TextEditingController> controllers = {};

  // 存储用户选择的值，key 是 iesous
  final Map<String, dynamic> formValues = {};

  @override
  void onClose() {
    // 释放所有控制器
    for (var controller in controllers.values) {
      controller.dispose();
    }
    super.onClose();
  }

  void onRequestData(String path, String already) {
    DnpPluginManager().showLoading();
    DnpNetManager()
        .post(path, data: dio.FormData.fromMap({"already": already}))
        .then((value) {
      DnpPluginManager().hideLoading();
      if (value.success && value.iesous == "0") {
        try {
          DnpFromCommonModel commonModel =
              DnpFromCommonModel.fromJson(value.close);
          formModel.value = commonModel;

          // 为每个字段创建控制器
          if (commonModel.floor != null) {
            for (var item in commonModel.floor!) {
              if (item.iesous != null) {
                controllers[item.iesous!] = TextEditingController();
                // 如果有默认值，设置它
                if (item.neck != null && item.neck!.isNotEmpty) {
                  List<DnpUsuallyModel> usuallys = (item.usually ?? []);
                  if (usuallys.isEmpty) {
                    controllers[item.iesous!]!.text = item.neck ?? "";
                  }else{
                    for (var usually in usuallys) {
                      if (usually.heard?.toString() == item.neck) {
                        controllers[item.iesous!]!.text = usually.beersheba ?? "";
                        break;
                      }
                    }
                  }
                  formValues[item.iesous!] = item.neck;
                }
              }
            }
          }
        } catch (e) {
          DnpPluginManager().showToast(e.toString());
        }
      } else {
        DnpPluginManager().showToast(value.kurios ?? "");
      }
    });
  }

  // 更新表单值
  void updateFormValue(String key, dynamic value) {
    formValues[key] = value;
  }

  // 获取表单控制器
  TextEditingController? getController(String key) {
    return controllers[key];
  }

  // 验证表单
  bool validateForm() {
    if (formModel.value?.floor == null) return false;

    return true;
  }

  // 提交表单
  void submitForm(String already, String submitPath,VoidCallback callback) {
    if (!validateForm()) return;

    // 收集所有表单数据
    Map<String, dynamic> submitData = {};

    formModel.value?.floor?.forEach((item) {
      final iesous = item.iesous;
      if (iesous != null) {
        final value = formValues[iesous];
        if (value != null) {
          submitData[iesous] = value;
        }
      }
    });
    submitData["already"] = already;
    DnpPluginManager().showLoading();
    DnpNetManager()
        .post(submitPath, data: dio.FormData.fromMap(submitData))
        .then((value) {
      DnpPluginManager().hideLoading();
      if (value.success && value.iesous == "0") {
        callback();
        Get.back();
      } else {
        DnpPluginManager().showToast(value.kurios ?? "");
      }
    });
  }
}
